﻿namespace EasyWeb.Web.UI.Html
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    using System.Web.Mvc;

    public static class EWTypeExtensions
    {
        public static string GetDisplayName(this Type type, string name)
        {
            if (type == null) { throw new ArgumentNullException("type"); }
            if (string.IsNullOrEmpty(name)) { throw new ArgumentException("The parameter name cannot be null or empty.", "name"); }

            var state = typeof(ViewDataDictionary<>).GetTypeInfo().MakeGenericType(type).GetConstructor(new Type[] { }).Invoke(new object[] { });
            var method = typeof(ModelMetadata).GetTypeInfo().GetMethod("FromStringExpression",
                BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
                null,
                new Type[] { typeof(string), typeof(ViewDataDictionary) },
                null);
            var metadata = (ModelMetadata)method.Invoke(null, new object[] { name, state });
            return metadata.DisplayName;
        }
    }
}
